package com.wchat.controller;

import com.lly835.bestpay.model.PayResponse;
import com.wchat.dto.OrderDto;
import com.wchat.enums.ResultEnum;
import com.wchat.exceptions.SellException;
import com.wchat.service.OrderService;
import com.wchat.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * Created by yangtianrui on 17/8/15.
 */
@Controller
//@RequestMapping("/pay")
@Slf4j
public class PayController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private PayService payService;

    @GetMapping("/pay")
    public ModelAndView index(@RequestParam("openid") String openid,
                              @RequestParam("orderId")String orderId,
                              @RequestParam("returnUrl")String returnUrl,
                              Map<String ,Object> map)
    {
        log.info("[openid]={}",openid);
        OrderDto orderDto =  orderService.findOne(orderId);
        if(orderDto == null)
        {
            log.error("[此订单不存在] orderId{}",orderId);
            throw  new SellException(ResultEnum.ORDER_NOT_EXIT);
        }
        // 发起支付:
//        orderDto.setBuyerOpenid(openId);
        PayResponse response = payService.create(orderDto);
        map.put("response",response);
        map.put("returnUrl",returnUrl+"/#/order/"+orderId);
        return new ModelAndView("pay/create",map);

    }

    @GetMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId,
                       @RequestParam("returnUrl") String returnUrl,Map<String,Object> map)
    {

        //  通过订单号中查询数据库 该订单是否存在 不存在的话抛出异常
       OrderDto orderDto =  orderService.findOne(orderId);
        log.info("openId={}",orderDto.getBuyerOpenid());
       if(orderDto == null)
       {
           log.error("[此订单不存在] orderId{}",orderId);
           throw  new SellException(ResultEnum.ORDER_NOT_EXIT);
       }
        // 发起支付
        orderDto.setBuyerOpenid(orderDto.getBuyerOpenid());
        PayResponse response = payService.create(orderDto);
        map.put("response",response);
        map.put("returnUrl",returnUrl);
        return new ModelAndView("pay/create",map);
    }

    /**
     *微信异步通知  @RequestBody 用于读取request请求中部分Body的数据,然后通过HttpMessageConverter进行解析,把相应的数据
     * 绑定到需要返回的对象上,再把HttpMessageConverter对象绑定到Controller方法的参数上。
     * @param notifyData
     */
    @PostMapping("/notify")
    public ModelAndView notifiy(@RequestBody String notifyData)
    {
        payService.notify(notifyData);
        //  返回给微信异步通知结果 写到模版里面去
        return  new ModelAndView("/pay/notify");
    }
}
